package cn.edu.ctbu.service.impl;

import cn.edu.ctbu.DTO.ShoppingCartDTO;
import cn.edu.ctbu.entity.ShoppingCart;
import cn.edu.ctbu.mapper.ShoppingCartMapper;
import cn.edu.ctbu.service.IShoppingCartService;
import cn.edu.ctbu.utils.JWTUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-05-12
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements IShoppingCartService {

    @Autowired
    HttpServletRequest httpServletRequest;
    @Override
    public void put(List<ShoppingCartDTO> list) {
        for (ShoppingCartDTO dto:list){
            ShoppingCart shoppingCart=new ShoppingCart();
            BeanUtils.copyProperties(dto,shoppingCart);
            shoppingCart.setCreateTime(LocalDateTime.now());
            save(shoppingCart);
        }
    }

    @Override
    public List<ShoppingCart> get() {
        //获得userid
        String token = httpServletRequest.getHeader("Authorization");
        Claims claims = JWTUtils.parseJWT(token);
        Long id = claims.get("id", Long.class);
        QueryWrapper wrapper=new QueryWrapper<>().eq("user_id",id);
        List<ShoppingCart> list = list(wrapper);
        return list;
    }
}
